package cn.virens;

import java.util.Arrays;

public class RingBuffer {
    private byte[] buffer;
    private int size;
    private int wpos;
    private int rpos;

    public RingBuffer(int size) {
        this.buffer = new byte[size];
        this.size = size;
        this.wpos = 0;
        this.rpos = 0;
    }

    public void push(byte b) {
        int nw = pos(wpos + 1);
        if (nw == rpos) {
            this.rpos = pos(rpos + 1);
        }

        this.buffer[wpos] = b;
        this.wpos = nw;
    }

    public int pop() {
        if (rpos == wpos) {
            return -1;
        }

        byte r = buffer[rpos];

        this.rpos = pos(rpos + 1);

        return r;
    }

    public int size() {
        if (wpos == rpos) {
            return 0;
        }

        if (wpos > rpos) {
            return wpos - rpos;
        }

        return size - rpos + wpos;
    }

    private int pos(int p) {
        return p % size;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(" R:").append(rpos);
        sb.append(" W:").append(wpos);
        sb.append(" T:").append(size());
        sb.append(" B:").append(Arrays.toString(buffer));
        return sb.toString();
    }
}
